from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
import uvicorn
import logging
import os

from config import settings
from routes.chat_routes import router as chat_router
from routes.qwen_poet_routes import router as qwen_poet_router

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 创建FastAPI应用
app = FastAPI(
    title="Vision Pro AI 对话后端",
    description="为Vision Pro WebXR应用提供AI对话和语音合成服务",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 确保音频目录存在并创建
audio_dir_abs = os.path.abspath(settings.audio_dir)
os.makedirs(audio_dir_abs, exist_ok=True)

# 挂载静态文件服务（用于音频文件） - 使用绝对路径确保正确挂载
app.mount("/audio", StaticFiles(directory=audio_dir_abs), name="audio")

# 包含路由
app.include_router(chat_router)
app.include_router(qwen_poet_router)

# 挂载静态文件服务
static_dir = os.path.join(os.path.dirname(__file__), "static")
if os.path.exists(static_dir):
    app.mount("/static", StaticFiles(directory=static_dir), name="static")

# 挂载前端静态文件服务（保留HTML文件访问）
frontend_dir = os.path.join(os.path.dirname(__file__), "frontend")
if os.path.exists(frontend_dir):
    app.mount("/", StaticFiles(directory=frontend_dir, html=True), name="frontend")

@app.get("/")
async def root():
    """根路径健康检查"""
    return {"message": "Vision Pro AI 对话后端服务运行中", "status": "healthy"}

@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {"message": "Vision Pro AI 对话后端服务运行中", "status": "healthy"}

@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    """全局异常处理器"""
    import traceback
    from datetime import datetime
    import uuid
    
    # 生成错误追踪ID
    error_id = str(uuid.uuid4())[:8]
    
    # 记录详细的错误信息
    error_detail = {
        "error_id": error_id,
        "error": str(exc),
        "type": type(exc).__name__,
        "path": str(request.url.path),
        "method": request.method,
        "timestamp": datetime.now().isoformat()
    }
    
    logger.error(f"未处理的异常 [{error_id}]: {error_detail}")
    logger.error(f"异常堆栈 [{error_id}]: {traceback.format_exc()}")
    
    # 根据异常类型返回不同的状态码
    if isinstance(exc, ValueError):
        status_code = 400
        detail = "请求参数错误"
    elif isinstance(exc, FileNotFoundError):
        status_code = 404
        detail = "请求的资源不存在"
    else:
        status_code = 500
        detail = "服务器内部错误"
    
    return JSONResponse(
        status_code=status_code,
        content={
            "detail": detail,
            "error_type": type(exc).__name__,
            "error_id": error_id,
            "timestamp": datetime.now().isoformat()
        }
    )

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=settings.host,
        port=settings.port,
        reload=settings.debug,
        log_level="info"
    )